package com.mooc.apigateway.interceptor;

import com.google.common.base.Joiner;
import com.mooc.apigateway.common.CommonConstants;
import com.mooc.apigateway.common.UserContext;
import com.mooc.apigateway.dao.UserDao;
import com.mooc.apigateway.model.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor{

	private static final String TOKEN_COOKIE = "token";

	@Autowired
	private UserDao userDao;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		Map<String, String[]> map = request.getParameterMap();
		map.forEach((k,v) -> {
			if (k.equals("errorMsg") || k.equals("successMsg") || k.equals("target")) {
				request.setAttribute(k, Joiner.on(",").join(v));
			}
		});
		//静态页面，错误页面，登录页面不进行拦截
	    String reqUri =	request.getRequestURI();
	    if (reqUri.startsWith("/static") || reqUri.startsWith("/error")
           ) {
			return true;
		}

		Cookie cookie = WebUtils.getCookie(request, TOKEN_COOKIE);
        if(cookie != null && StringUtils.isNoneBlank(cookie.getValue())){
        User user =	userDao.getUserByToken(cookie.getValue());
        if(user != null){
        	//保存用户信息，用于页面取值
        	request.setAttribute(CommonConstants.LOGIN_USER_ATTRIBUTE, user);
        	request.setAttribute(CommonConstants.USER_ATTRIBUTE, user);
		    UserContext.setUser(user);
        }

		}

		return true;
	}


	/**
	 * 每次controller处理逻辑前都要去判断jwt
	 * 处理完逻辑后，都要把他设置到cookie里面，以便下次请求可以携带jwt进行请求
	 * @param
	 * @param response
	 * @param handler
	 * @param modelAndView
	 * @throws Exception
	 */
	@Override
	public void postHandle(HttpServletRequest req, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
         String requestURI = req.getRequestURI();
         //1.不处理静态只有和错误页面的请求
		 if(requestURI.startsWith("/static") || requestURI.startsWith("/error")){
		 	return;
		 }
		User user = UserContext.getUser();
		 if(user != null && StringUtils.isNotBlank(user.getToken())){
         //2.登出请求要把cookie值置空
			 String token = requestURI.startsWith("logout") ? "" : user.getToken();
			 Cookie cookie = new Cookie(TOKEN_COOKIE, token);
			 cookie.setPath("/");
			 cookie.setHttpOnly(false);
			 response.addCookie(cookie);
		 }


	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserContext.remove();
	}
	

}
